package softtech.apps.autoanswerphonecall;

import java.io.File;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;

public class ListVoiceMessageAdapter extends BaseAdapter{

	private Context context;

	TextView tvVoiceMessageItem;
	ImageButton btnImageDel;
	
	private static final String AUDIO_RECORDER_FOLDER = "VoiceMessage";

	private File folder;
	private File files[];
	
	ArrayList<String> VoiceMessageReceived = new ArrayList<String>();
	ArrayList<String> VoiceMessageReceivedTitle = new ArrayList<String>();
	String TAG = "TAG";
	
	// Static var to hold message is choose
	public ListVoiceMessageAdapter(Context ctx) {
		super();
		this.context = ctx;
		String filepath = Environment.getExternalStorageDirectory().getPath();
		folder = new File(filepath, AUDIO_RECORDER_FOLDER);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		files = folder.listFiles();
		
		if (!files.equals(null)) {
			for (File a : files) {
				VoiceMessageReceived.add(a.getAbsolutePath());
				
				Log.d("MUSIC", "Duong dan file am thanh = "+a.getAbsolutePath());
				
				VoiceMessageReceivedTitle.add(a.getName());
			}
		}
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return VoiceMessageReceived.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(final int position,View convertView, ViewGroup parent) {
		
		// TODO Auto-generated method stub
		LayoutInflater inflater = (LayoutInflater) context
		        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		convertView = inflater.inflate(R.layout.list_voice_message_custom, parent, false);
		tvVoiceMessageItem = (TextView) convertView.findViewById(R.id.tvVoiceMessageItem);
		tvVoiceMessageItem.setText(VoiceMessageReceivedTitle.get(position));
		btnImageDel = (ImageButton) convertView.findViewById(R.id.btnImageDel);
		btnImageDel = (ImageButton) convertView.findViewById(R.id.btnImageDel);
		
		tvVoiceMessageItem.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				PlayMusic(VoiceMessageReceived.get(position));
				Log.d("MUSIC","Click to play music");
			}
		});
		
		final AlertDialog.Builder builder = new AlertDialog.Builder(context);
	    final DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
	        @Override
	        public void onClick(DialogInterface dialog, int which) {
	            switch (which){
	            case DialogInterface.BUTTON_POSITIVE:
	                //Yes button clicked
					String file_path = VoiceMessageReceived.get(position);
					Log.d(TAG, "File path to delete = "+file_path);
					File file = new File(file_path);
					boolean deleted = file.delete();
					VoiceMessageReceived.remove(position);
					Log.d(TAG, "Just delete file with path "+file_path);
					notifyDataSetChanged();
	                break;

	            case DialogInterface.BUTTON_NEGATIVE:
	                //No button clicked
	                break;
	            }
	        }
	    };
		btnImageDel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				 builder.setMessage("Are you sure?").setNegativeButton("No", dialogClickListener)
			     .setPositiveButton("Yes", dialogClickListener)
			        .show();
			}
		});
		//convertView.setBackgroundColor(Color.WHITE);
		return convertView;// return a row of listview
	}
	
	private void PlayMusic(String filePath) {

		AudioManager am = (AudioManager) context.getSystemService(
				Context.AUDIO_SERVICE);
		am.setMode(AudioManager.STREAM_MUSIC);
		// am.setSpeakerphoneOn(true);

		am.setStreamVolume(AudioManager.STREAM_MUSIC,
				am.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
		
		am.setSpeakerphoneOn(true);
		MediaPlayer mediaPlayer = new MediaPlayer();
		mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
			@Override
			public void onPrepared(MediaPlayer mp) {
				// Do something. For example: playButton.setEnabled(true);
//				mp.start();
				
			}
		});
		mediaPlayer.setLooping(false);
		mediaPlayer.setVolume(am.getStreamMaxVolume(AudioManager.STREAM_MUSIC), am.getStreamMaxVolume(AudioManager.STREAM_MUSIC));

		try {
			mediaPlayer.setDataSource(filePath);
			mediaPlayer.prepare();
		} catch (Exception e) {
			e.printStackTrace();
		}
		mediaPlayer.start();
		
		mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

			@Override
			public void onCompletion(MediaPlayer mp) {
				// TODO Auto-generated method stub
				mp.stop();
				mp.release();
				mp = null;
			}

		});

	}

}
